package demo19_Lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author kunkun
 * @className Test04_DiySpinLock
 * @Description 测试自定义自旋锁
 * @date 2025/3/8 22:50
 */
public class Test05_DiySpinLock_Test {
    public static void main(String[] args) throws InterruptedException {
        //获得自定义锁
        Test04_DiySpinLock lock = new Test04_DiySpinLock();

        new Thread(()->{
            lock.lock();    //开启自定义锁，A获得锁
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                lock.unlock();  //解锁，之后B才能获得锁
            }

        },"A").start();     //A获得锁，继续执行，B持续等待

        TimeUnit.SECONDS.sleep(1);

        new Thread(()->{
            lock.lock();    //开启自定义锁，B获得锁
            System.out.println(Thread.currentThread().getName()+"开始获得锁");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                lock.unlock();
            }

        },"B").start();     //B获得锁，继续执行



    }



}
